package com.txby.web;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.txby.config.RouteConfig;
import com.txby.service.FileService;

import lombok.extern.slf4j.Slf4j;

@Slf4j
@RestController
public class FileController {

    @Resource
    private FileService fileService;
    @Autowired
    private RouteConfig routeConfig;
    /**
     * 文件上传
     * @param files
     * @param filePath
     * @return
     */
    @PostMapping("uploadFiles")
    public Map uploadFiles(@RequestParam(value = "files",required = false) MultipartFile[] files,String filePath,String token) {
        Map<String, Object> returnMap = new HashMap<>();
        if(null!=routeConfig.getToken()&&!"".equals(routeConfig.getToken())&&routeConfig.getToken().equals(token)){
        	if(files == null) {
        		log.warn("Client no upload files");
        		returnMap.put("errcode", 1);
        		returnMap.put("errmsg", "上传失败");
        	}else {
        		for(MultipartFile f: files){
        			if(f.getSize()>new Long(routeConfig.getMaxFileSize())){//5m
        				log.warn("Client no upload files");
                		returnMap.put("errcode", 1);
                		returnMap.put("errmsg", "上传失败大于5m");
        				return returnMap;
        			}
        			
        		}
        		String[] fileNames =  Arrays.stream(files).map(file -> fileService.saveFile(file,filePath)).toArray(String[]::new);
        		for(String fileUrl:fileNames){
        			if(fileUrl.startsWith("This")){
            			returnMap.put("errcode", 1);
            			returnMap.put("errmsg", "上传失败,不支持文件类型");
            			return returnMap;
            		}	
        		}
        		returnMap.put("fileUrls", fileNames);
        		returnMap.put("errcode", 0);
        		returnMap.put("errmsg","成功");
        	}
        }else{
        	
        	returnMap.put("errcode", 1);
    		returnMap.put("errmsg", "上传失败");
        }
        return returnMap;
    }

    /**
     * 文件下载
     * @param filePath
     * @return
     */
    @GetMapping("downFile")
    public String down(HttpServletResponse res,String filePath) {
		String fileName=filePath.substring(filePath.lastIndexOf("/")+1,filePath.length());
//		String fileName = "upload.jpg";
		res.setHeader("content-type", "application/octet-stream");
		res.setContentType("application/octet-stream");
		res.setHeader("Content-Disposition", "attachment;filename=" + fileName);
		byte[] buff = new byte[1024];
		BufferedInputStream bis = null;
		OutputStream os = null;
		try {
			os = res.getOutputStream();
			bis = new BufferedInputStream(new FileInputStream(new File(routeConfig.getHardDisk()+File.separator+filePath)));
			int i = bis.read(buff);
			while (i != -1) {
				os.write(buff, 0, buff.length);
				os.flush();
				i = bis.read(buff);
			}
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (bis != null) {
				try {
					bis.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		System.out.println("success");
        return "success";
    }
    
	 
    /**
     * 单个文件上传
     * @param file
     * @param filePath
     * @return
     */
    @PostMapping("uploadFile")
    public Map uploadFile(@RequestParam(value = "file",required = false) MultipartFile file,String filePath,String token) {
        Map<String, Object> returnMap = new HashMap<>();
        if(null!=routeConfig.getToken()&&!"".equals(routeConfig.getToken())&&routeConfig.getToken().equals(token)){
        	if(file == null) {
        		log.warn("Client no upload files");
        		returnMap.put("errcode", 1);
        		returnMap.put("errmsg", "上传失败");
        	}else {
        			if(file.getSize()>new Long(routeConfig.getMaxFileSize())){
        				log.warn("Client no upload files");
                		returnMap.put("errcode", 1);
                		returnMap.put("errmsg", "上传失败大于"+new Long(routeConfig.getMaxFileSize())/1000000+"M");
        				return returnMap;
        			}
        		returnMap.put("errcode", 0);
        		String fileUrl=fileService.saveFile(file,filePath);
        		returnMap.put("fileUrl",fileUrl);
        		returnMap.put("errmsg","成功");
        		if(fileUrl.startsWith("This")){
        			returnMap.put("errcode", 1);
        			returnMap.put("errmsg", "上传失败,不支持文件类型");
        		}
        	}
        }else{
        	returnMap.put("errcode", 1);
    		returnMap.put("errmsg", "上传失败");
        }
        return returnMap;
    }

    /**
     * 删除文件
     * @param filePath
     * @return
     */
    @PostMapping("dropFile")
    public  Map dropFile(String filePath,String token) {
    	Map<String,Object> returnMap = new HashMap<>();
    	if(null!=routeConfig.getToken()&&!"".equals(routeConfig.getToken())&&routeConfig.getToken().equals(token)){
    		String returnStr = fileService.dropFile(filePath);
    		log.info(returnStr+"and dropfile:"+filePath);
    		if("successful operation".equals(returnStr)) {
    			returnMap.put("errcode", 0);
        		returnMap.put("errmsg", "删除成功");
    		}else {
    			returnMap.put("errcode", 1);
        		returnMap.put("errmsg", "删除失败");
    		}
    	}else{
    		
    		returnMap.put("errcode", 1);
    		returnMap.put("errmsg", "删除失败");
    	}
        return  returnMap;
    }
    
    
   
 

}
